package com.hrt.manage.product.controllor;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hrt.base.BaseController;
import com.hrt.bean.GiftDetail;
import com.hrt.bean.GiftGroup;
import com.hrt.bean.GiftInfor;
import com.hrt.manage.product.service.GiftDetailService;
import com.hrt.manage.product.service.GiftGroupService;
import com.hrt.manage.product.service.GiftInforService;
import com.hrt.util.PageUtils;

@Controller
@RequestMapping("manage/giftDetail")
public class GiftDetailController extends BaseController<GiftDetail>{
	//礼品规格
	@Autowired
	private GiftDetailService giftDetailService;
	//礼品基本信息
	@Autowired
	private GiftInforService giftInfoService;
	//礼品组合
	@Autowired
	private GiftGroupService giftGroupService;
	
	private List<GiftInfor> giftInfors;
	private GiftInfor giftInfor;
	private GiftDetail giftDetail;
	
	public GiftInfor getGiftInfor() {
		return giftInfor;
	}
	public void setGiftInfor(GiftInfor giftInfor) {
		this.giftInfor = giftInfor;
	}
	
	public List<GiftInfor> getGiftInfors() {
		return giftInfors;
	}
	public void setGiftInfors(List<GiftInfor> giftInfors) {
		this.giftInfors = giftInfors;
	}

	public GiftDetail getGiftDetail() {
		giftDetail = new GiftDetail();
		return giftDetail;
	}
	public void setGiftDetail(GiftDetail giftDetail) {
		this.giftDetail = giftDetail;
	}
	
	/**分页*/
	@RequestMapping(value = "/queryByPage")
	@ResponseBody
	public Map<String, PageUtils<GiftDetail>> queryByPage(
			@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
			@RequestParam(value = "pageSize", required = false) Integer pageSize,
			@RequestParam(value = "id", required = true) Long giId,
			HttpServletRequest request) {
		Map<String, PageUtils<GiftDetail>> resultMap = new HashMap<String, PageUtils<GiftDetail>>();

		if (pageSize == null || "".equals(pageSize)) {
			pageSize = 30;
		}
		if (pageIndex == null || "".equals(pageIndex)) {
			pageIndex = 1;
		}
		setPageIndex(pageIndex);

		setPageSize(pageSize);
		List<GiftDetail> resultList = new ArrayList<GiftDetail>();
		setTotalCount(giftDetailService.totalCount());
		if (giId == null) {
			throw new RuntimeException("礼品编号有误");
		} else {
			giftInfor = this.giftInfoService.getById(giId);
			resultList = giftDetailService.queryById(giId, pageIndex,
					pageSize);
			/**demo*/
			int i = 0;
			List<GiftDetail> listGD = giftDetailService.searchIspush(giftInfor);
			for (Iterator<GiftDetail> iterGDs = listGD.iterator(); iterGDs.hasNext();) {
				giftDetail = iterGDs.next();
				if(giftDetail.getIspush()==1){
					i++;
				}
			}
			if(i!=0){
				giftInfor.setIspush(1);
				this.giftInfoService.updateGiftInfor(giftInfor);
			}else{
				giftInfor.setIspush(0);
				this.giftInfoService.updateGiftInfor(giftInfor);
			}
			/**=============*/
		}
		setList(resultList);
		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));
		page = this.getPage();
		resultMap.put("pageResult", page);
		return resultMap;
	}
	
	/**
	 * 加载一个礼品规格实体
	 * 
	 * @param giftDetaiId
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/loadGiftDetail")
	@ResponseBody
	public Map loadGiftDetail(
			@RequestParam(value = "id", required = true) Long giftDetaiId,
			HttpServletRequest request, HttpServletResponse response) {
		Map map = new HashMap();
		if (giftDetaiId != null && !"".equals(giftDetaiId)) {
			GiftDetail giftDetail = this.giftDetailService.getById(new Long(
					giftDetaiId));
			if (giftDetail != null) {
				map = transBean2Map(giftDetail);
			}
		}
		return map;
	}

	/**
	 * 查看
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/list")
	public ModelAndView list(
			@RequestParam(value = "id", required = true) Long giId,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView();
		if(giId!=null){
		List list = new ArrayList();
		giftInfor = this.giftInfoService.getById(giId);

		list = giftDetailService.queryById(giId, getPageIndex(),
				getPageSize());
		setTotalCount(giftDetailService.totalCount());
		this.setList(list);
		
		/**demo*/
		int i = 0;
		List<GiftDetail> listGD = giftDetailService.searchIspush(giftInfor);
		for (Iterator<GiftDetail> iterGDs = listGD.iterator(); iterGDs.hasNext();) {
			giftDetail = iterGDs.next();
			if(giftDetail.getIspush()==1){
				i++;
			}
		}
		if(i!=0){
			giftInfor.setIspush(1);
			this.giftInfoService.updateGiftInfor(giftInfor);
		}else{
			giftInfor.setIspush(0);
			this.giftInfoService.updateGiftInfor(giftInfor);
		}
		/**=============*/
		
		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));

		page = this.getPage();
		giftInfors = this.giftInfoService.searchDelAll();
		view.addObject("giId", giId);
		view.addObject("giftInfors", giftInfors);
		view.addObject("pageResult", page);
		}else{
		}
		return view;
		
	}

	/**
	 * 删除
	 * */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody Long[] delete(
			@RequestParam(value = "ids", required = true) String ids,
			HttpServletResponse response) throws IOException {
		Long[] idArr = null;
		if (ids != null) {
			if (ids.indexOf(",") != -1) {
				String[] idStrs = ids.split(",");
				idArr = new Long[idStrs.length];
				for (int idx = 0; idx < idStrs.length; idx++) {
					idArr[idx] = Long.parseLong(idStrs[idx]);
					
					/**删除礼品组合*/
					List<GiftGroup> listgiftGroup= this.giftGroupService.getGroupIdforId(idArr[idx]);
					if(listgiftGroup!=null && listgiftGroup.size()>0){
						for (Iterator<GiftGroup> iterGroup = listgiftGroup.iterator(); iterGroup.hasNext();) {
							GiftGroup gigr = (GiftGroup) iterGroup.next();
							try {
								//删除礼品组合
								this.giftGroupService.deleteByOneId(gigr.getId());
							} catch (Exception e) {
								e.printStackTrace();
							}
				        }
					}
					
				}
			} else {
				idArr = new Long[] { Long.parseLong(ids) };
				//删除礼品组合
				List<GiftGroup> listgiftGroup= this.giftGroupService.getGroupIdforId(Long.parseLong(ids));
				if(listgiftGroup!=null && listgiftGroup.size()>0){
					for (Iterator<GiftGroup> iterGroup = listgiftGroup.iterator(); iterGroup.hasNext();) {
						GiftGroup gigr = (GiftGroup) iterGroup.next();
						try {
							//删除礼品组合
							this.giftGroupService.deleteByOneId(gigr.getId());
						} catch (Exception e) {
							e.printStackTrace();
						}
			        }
				}
			}

		}
		try {
			giftDetailService.deleteById(idArr);
			return idArr;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}
	
	/**
	 * 上架
	 * */
	@RequestMapping(value = "/shelve", method = RequestMethod.POST)
	public @ResponseBody Long[] shelve(
			@RequestParam(value = "ids", required = true) String ids,
			HttpServletResponse response) throws IOException {
		Long[] idArr = null;
		if (ids != null) {
			if (ids.indexOf(",") != -1) {
				String[] idStrs = ids.split(",");
				idArr = new Long[idStrs.length];
				for (int idx = 0; idx < idStrs.length; idx++) {
					idArr[idx] = Long.parseLong(idStrs[idx]);
				}
			} else {
				idArr = new Long[] { Long.parseLong(ids) };
			}
		}
		try {
			giftDetailService.shelveById(idArr);

			return idArr;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 下架
	 * */
	@RequestMapping(value = "/unShelve", method = RequestMethod.POST)
	public @ResponseBody Long[] unShelve(
			@RequestParam(value = "ids", required = true) String ids,
			HttpServletResponse response) throws IOException {
		Long[] idArr = null;
		if (ids != null) {
			if (ids.indexOf(",") != -1) {
				String[] idStrs = ids.split(",");
				idArr = new Long[idStrs.length];
				for (int idx = 0; idx < idStrs.length; idx++) {
					idArr[idx] = Long.parseLong(idStrs[idx]);
				}
			} else {
				idArr = new Long[] { Long.parseLong(ids) };
			}
		}
		try {
			giftDetailService.unShelveById(idArr);
			return idArr;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 跳转到添加页面
	 * */
	@RequestMapping(value = "/add")
	@ResponseBody
	public Map<String, Object> add(
			@RequestParam(value = "id", required = true) Long giId,
			HttpServletRequest request) {
		if (giId != null && !"".equals(giId)) {
			giftInfor = giftInfoService.getById(giId);
		}
		giftDetail = getGiftDetail();
		giftDetail.setGiftCode(giftInfor.getGiftCode());
		giftDetail.setGiftName(giftInfor.getGiftName());
		giftDetail.setGiftInfor(giftInfor);

		Map<String, Object> map = BaseController.transBean2Map(giftDetail);
		return map;

	}
	/**
	 * 根据礼品规格id返回礼品规格数量 
	 * @param giftDetailId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getGiftDetailTotals")
	@ResponseBody
	public Long getGiftDetailTotals(@RequestParam(value = "id", required = true) Long giftDetailId,
			HttpServletRequest request){
		System.out.println("fuck-------------------------------------"+giftDetailId);
		return giftDetailService.getGiftTotals(giftDetailId);
		
	}

	
	/**
	 * 添加
	 * */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public void save(@ModelAttribute("giftDetail") GiftDetail gd, 
			HttpServletRequest request, HttpServletResponse response) {
		try {
			Timestamp createTime = this.giftDetailService.getDate();
			gd.setCreateTime(createTime);
			giftDetailService.addGiftDetail(gd);
			response.sendRedirect("list.do?id="+gd.getGiftInfor().getId());
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 跳转到修改页面
	 * */
	@SuppressWarnings({ "rawtypes" })
	@RequestMapping(value = "/show")
	@ResponseBody
	public Map show(@RequestParam(value = "id", required = true) String gdId,
			HttpServletRequest request, HttpServletResponse response) {

		Map map = new HashMap();
		if (gdId != null && !"".equals(gdId)) {
			giftDetail = this.giftDetailService.getById(new Long(gdId));
			if (giftDetail != null) {
				map = transBean2Map(giftDetail);
			}
		}
		return map;
	}

	/**
	 * 修改
	 * */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public void update(@ModelAttribute("giftDetail") GiftDetail gd,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			Timestamp editTime = this.giftDetailService.getDate();
			gd.setEditTime(editTime);
			giftDetailService.updateGiftDetail(gd);
			response.sendRedirect("list.do?id="+gd.getGiftInfor().getId());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
